import 'package:get/get.dart';
import 'package:realm/realm.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

import '../models/contract_model.dart';
import 'system_tray_service.dart';

class ContractService extends GetxService {
  final SystemTrayService _systemTrayService = SystemTrayService();

  final expiringContracts = <Contract>[].obs;

  Future<Realm> getRealm() async {
    final config = Configuration.local([Contract.schema]);
    return Realm(config);
  }

  @override
  void onInit() {
    super.onInit();
    tz.initializeTimeZones();
    _initNotifications();
    _scheduleDailyCheck();
    _checkExpiringContracts();
  }

  Future<void> _checkExpiringContracts() async {
    await getExpiringContracts();
    for (final contract in expiringContracts) {
      await showReminder(contract);
    }
  }

  Future<void> _initNotifications() async {
    await _systemTrayService.initSystemTray();
  }

  Future<void> _scheduleDailyCheck() async {
    final now = DateTime.now();
    final checkTime = DateTime(now.year, now.month, now.day, 9, 0, 0); // 每天9点检查

    try {
      final scheduledTime = _nextInstanceOfTime(checkTime);

      await _systemTrayService.scheduleNotification(
        id: 1,
        title: '合同到期检查',
        body: '正在检查即将到期的合同...',
        scheduledDate: scheduledTime,
        repeatInterval: const Duration(days: 1),
        payload: 'daily_check',
      );

      _systemTrayService.onNotificationClicked.listen((payload) {
        if (payload == 'daily_check') {
          _checkExpiringContracts();
        }
      });
    } catch (e) {
      Get.snackbar('计划任务设置失败', '无法设置每日检查计划：$e');
    }
  }

  tz.TZDateTime _nextInstanceOfTime(DateTime time) {
    final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
    tz.TZDateTime scheduledDate = tz.TZDateTime.from(time, tz.local);

    if (scheduledDate.isBefore(now)) {
      scheduledDate = scheduledDate.add(const Duration(days: 1));
    }

    return scheduledDate;
  }

  Future<void> getExpiringContracts() async {
    final now = DateTime.now();
    final oneMonthLater = now.add(const Duration(days: 30));

    // TODO: 实现从数据库查询即将到期合同
    expiringContracts.value = []; // 替换为实际的数据库查询结果
  }

  Future<void> showReminder(Contract contract) async {
    Get.defaultDialog(
      title: "合同到期提醒",
      middleText:
          "合同 ${contract.contractNumber} 即将于${contract.expirationDate}到期，请及时续约",
      textConfirm: "续约",
      textCancel: "放弃",
      onConfirm: () => handleRenew(contract),
      onCancel: () => handleAbandon(contract),
    );
  }

  Future<void> handleRenew(Contract contract) async {
    try {
      final realm = await getRealm();

      // 查找需要续约的合同
      final existing = realm
          .query<Contract>(
            'contractNumber == "${contract.contractNumber}"',
          )
          .firstOrNull;

      if (existing != null) {
        realm.write(() {
          // 延长合同期限一年
          final newExpiration = DateTime(existing.expirationDate.year + 1,
              existing.expirationDate.month, existing.expirationDate.day);
          existing.expirationDate = newExpiration;

          // 更新续约状态
          existing.isRenewed = true;
        });

        Get.snackbar('续约成功', '合同 ${contract.contractNumber} 已成功续约');
      } else {
        Get.snackbar('续约失败', '未找到该合同');
      }
    } catch (e) {
      Get.snackbar('续约失败', '发生错误：$e');
    }

    Get.back();
    await getExpiringContracts(); // 更新列表
  }

  Future<void> handleAbandon(Contract contract) async {
    try {
      final realm = await getRealm();

      // 查找需要放弃的合同
      final existing = realm
          .query<Contract>(
            'contractNumber == "${contract.contractNumber}"',
          )
          .firstOrNull;

      if (existing != null) {
        realm.write(() {
          // 标记合同为已放弃
          existing.isAbandoned = true;

          // 添加放弃日期
          existing.abandonDate = DateTime.now();
        });

        Get.snackbar('操作成功', '合同 ${contract.contractNumber} 已标记为放弃');
      } else {
        Get.snackbar('操作失败', '未找到该合同');
      }
    } catch (e) {
      Get.snackbar('操作失败', '发生错误：$e');
    }

    Get.back();
    await getExpiringContracts(); // 更新列表
  }

  Future<void> batchSaveContracts(List<Contract> contracts) async {
    try {
      if (contracts.isEmpty) return;

      // 开启事务
      final realm = await getRealm();
      realm.write(() {
        for (final contract in contracts) {
          // 检查是否已存在相同合同编号
          final existing = realm
              .query<Contract>(
                'contractNumber == "${contract.contractNumber}"',
              )
              .firstOrNull;

          if (existing == null) {
            // 新增合同
            realm.add(contract);
          } else {
            // 更新现有合同
            existing.customerName = contract.customerName;
            existing.projectName = contract.projectName;
            existing.contractDate = contract.contractDate;
            existing.expirationDate = contract.expirationDate;
          }
        }
      });
    } catch (e) {
      throw Exception('批量保存合同失败：$e');
    }
  }
}
